The goal of this notebook is to implement your own binary decision tree classifier. You will:
Important Note: In this assignment, we will focus on building decision trees where the data contain only binary (0 or 1) features. This allows us to avoid dealing with:
This assignment may be challenging, so brace yourself :)
Make sure you have the latest version of GraphLab Create.
import graphlab as gl
print('gl.version: %s' % (gl.version))
gl.canvas.set_target('ipynb')
import math
import string
# my imports
import pandas as pd
import numpy as np
from six.moves import cPickle as pickle
from types import MethodType
def value_counts( self ):
import pandas as pd
pdDf = self.to_dataframe()
for ftr in pdDf.columns:
print(pdDf[ftr].value_counts())
#SFrame.value_counts = MethodType(value_counts, None, SFrame)
#setattr(SFrame, 'value_counts', value_counts)
#setattr(glbObsAll, 'value_counts', value_counts)
We will be using the same LendingClub dataset as in the previous assignment.
glbObsAll = gl.SFrame('data/lending-club-data.gl/')
print(glbObsAll.shape)
glbObsAll.show()
print(glbObsAll)
Like the previous assignment, we reassign the labels to have +1 for a safe loan, and -1 for a risky (bad) loan.
glbObsAll['safe_loan'] = glbObsAll['bad_loans'].apply(lambda x : +1 if x==0 else -1)
glbObsAll['safe_loan'].show(view = 'Categorical')
#glbObsAll = glbObsAll.remove_column('bad_loans')
glbObsAll = glbObsAll.remove_column('bad_loans')
#pickle_file = 'module-5-decision-tree-assignment-2.pickle'
#glbObsAll.to_pickle(pickle_file)
glbObsAll.save('data/module-5-decision-tree-assignment-2.gl')
Unlike the previous assignment where we used several features, in this assignment, we will just be using 4 categorical features:
Since we are building a binary decision tree, we will have to convert these categorical features to a binary representation in a subsequent section using 1-hot encoding.
features = ['grade', # grade of the loan
'term', # the term of the loan
'home_ownership', # home_ownership status: own, mortgage or rent
'emp_length', # number of years of employment
]
target = 'safe_loan'
glbObsAll = glbObsAll[features + [target]]
Let's explore what the dataset looks like.
print(glbObsAll.shape)
glbObsAll.show()
glbObsAll
Just as we did in the previous assignment, we will undersample the larger class (safe glbObsAll) in order to balance out our dataset. This means we are throwing away many data points. We use seed=1 so everyone gets the same results.
glbObsSfe = glbObsAll[glbObsAll[target] == +1]
glbObsRsk = glbObsAll[glbObsAll[target] == -1]
# Since there are less risky loans than safe loans, find the ratio of the sizes
# and use that percentage to undersample the safe loans.
percentage = len(glbObsRsk)/float(len(glbObsSfe))
glbObsSfeSmp = glbObsSfe.sample(percentage, seed = 1)
#risky_glbObsAll = glbObsRsk
glbObsSmp = glbObsRsk.append(glbObsSfeSmp)
print "Percentage of safe loans : %.2f%%" % \
(len(glbObsSfeSmp) * 100.0 / float(len(glbObsSmp)))
print "Percentage of risky loans : %.2f%%" % \
(len(glbObsRsk) * 100.0 / float(len(glbObsSmp)))
print "Total number of loans in our new dataset :", len(glbObsSmp)
Note: There are many approaches for dealing with imbalanced data, including some where we modify the learning algorithm. These approaches are beyond the scope of this course, but some of them are reviewed in this paper. For this assignment, we use the simplest possible approach, where we subsample the overly represented class to get a more balanced dataset. In general, and especially when the data is highly imbalanced, we recommend using more advanced methods.
In this assignment, we will implement binary decision trees (decision trees for binary features, a specific case of categorical variables taking on two values, e.g., true/false). Since all of our features are currently categorical features, we want to turn them into binary features.
For instance, the home_ownership feature represents the home ownership status of the loanee, which is either own, mortgage or rent. For example, if a data point has the feature
{'home_ownership': 'RENT'}
we want to turn this into three features:
{
'home_ownership = OWN' : 0,
'home_ownership = MORTGAGE' : 0,
'home_ownership = RENT' : 1
}
Since this code requires a few Python and GraphLab tricks, feel free to use this block of code as is. Refer to the API documentation for a deeper understanding.
#glbObsSmp = risky_glbObsAll.append(glbObsSfeSmp)
for feature in features:
glbObsSmp_one_hot_encoded = glbObsSmp[feature].apply(lambda x: {x: 1})
glbObsSmp_unpacked = glbObsSmp_one_hot_encoded.unpack(column_name_prefix=feature)
# Change None's to 0's
for column in glbObsSmp_unpacked.column_names():
glbObsSmp_unpacked[column] = glbObsSmp_unpacked[column].fillna(0)
glbObsSmp.remove_column(feature)
glbObsSmp.add_columns(glbObsSmp_unpacked)
glbObsSmp.save('data/module-5-decision-tree-assignment-2_glbObsSmp.gl')
Let's see what the feature columns look like now:
features = glbObsSmp.column_names()
features.remove('safe_loan') # Remove the response variable
features
print "Number of features (after binarizing categorical variables) = %s" % len(features)
Let's explore what one of these columns looks like:
glbObsSmp['grade.A']
This column is set to 1 if the loan grade is A and 0 otherwise.
Checkpoint: Make sure the following answers match up.
print "Total number of grade.A loans : %s" % glbObsSmp['grade.A'].sum()
print "Expected answer : 6422"
We split the data into a train test split with 80% of the data in the training set and 20% of the data in the test set. We use seed=1 so that everyone gets the same result.
glbObsFit, glbObsOOB = glbObsSmp.random_split(.8, seed=1)
print(glbObsFit.shape)
print(glbObsOOB.shape)
In this section, we will implement binary decision trees from scratch. There are several steps involved in building a decision tree. For that reason, we have split the entire assignment into several sections.
Recall from the lecture that prediction at an intermediate node works by predicting the majority class for all data points that belong to this node.
Now, we will write a function that calculates the number of missclassified examples when predicting the majority class. This will be used to help determine which feature is the best to split on at a given node of the tree.
Note: Keep in mind that in order to compute the number of mistakes for a majority classifier, we only need the label (y values) of the data points in the node.
Steps to follow :
Now, let us write the function getNMistakesIntermediateNode which computes the number of misclassified examples of an intermediate node given the set of labels (y values) of the data points contained in the node. Fill in the places where you find ## YOUR CODE HERE. There are three places in this function for you to fill in.
def getNMistakesIntermediateNode(labelsNode):
# Corner case: If labelsNode is empty, return 0
if len(labelsNode) == 0:
return 0
# Count the number of 1's (safe loans)
## YOUR CODE HERE
nSfeLoans = len(labelsNode[labelsNode == +1])
# Count the number of -1's (risky loans)
## YOUR CODE HERE
nRskLoans = len(labelsNode[labelsNode == -1])
# Return the number of mistakes that the majority classifier makes.
## YOUR CODE HERE
if (nSfeLoans >= nRskLoans):
nMistakes = nRskLoans
else:
nMistakes = nSfeLoans
return(nMistakes)
Because there are several steps in this assignment, we have introduced some stopping points where you can check your code and make sure it is correct before proceeding. To test your getNMistakesIntermediateNode function, run the following code until you get a Test passed!, then you should proceed. Otherwise, you should spend some time figuring out where things went wrong.
# Test case 1
example_labels = gl.SArray([-1, -1, 1, 1, 1])
if getNMistakesIntermediateNode(example_labels) == 2:
print 'Test passed!'
else:
print 'Test 1 failed... try again!'
# Test case 2
example_labels = gl.SArray([-1, -1, 1, 1, 1, 1, 1])
if getNMistakesIntermediateNode(example_labels) == 2:
print 'Test passed!'
else:
print 'Test 2 failed... try again!'
# Test case 3
example_labels = gl.SArray([-1, -1, -1, -1, -1, 1, 1])
if getNMistakesIntermediateNode(example_labels) == 2:
print 'Test passed!'
else:
print 'Test 3 failed... try again!'
The function getFeatureSplitBest takes 3 arguments:
The function will loop through the list of possible features, and consider splitting on each of them. It will calculate the classification error of each split and return the feature that had the smallest classification error when split on.
Recall that the classification error is defined as follows: $$ \mbox{classification error} = \frac{\mbox{# mistakes}}{\mbox{# total examples}} $$
Follow these steps:
This may seem like a lot, but we have provided pseudocode in the comments in order to help you implement the function correctly.
Note: Remember that since we are only dealing with binary features, we do not have to consider thresholds for real-valued features. This makes the implementation of this function much easier.
Fill in the places where you find ## YOUR CODE HERE. There are five places in this function for you to fill in.
def getFeatureSplitBest(data, features, target):
featureBest = None # Keep track of the best feature
errorBest = 10 # Keep track of the best error so far
# Note: Since error is always <= 1, we should intialize it with something larger than 1.
# Convert to float to make sure error gets computed correctly.
nObs = float(len(data))
# Loop through each feature to consider splitting on that feature
for feature in features:
# The left split will have all data points where the feature value is 0
splitLft = data[data[feature] == 0]
# The right split will have all data points where the feature value is 1
## YOUR CODE HERE
splitRgt = data[data[feature] != 0]
# Calculate the number of misclassified examples in the left split.
# Remember that we implemented a function for this!
# (It was called getNMistakesIntermediateNode)
# YOUR CODE HERE
nMistakesLft = getNMistakesIntermediateNode(splitLft[target])
# Calculate the number of misclassified examples in the right split.
## YOUR CODE HERE
nMistakesRgt = getNMistakesIntermediateNode(splitRgt[target])
# Compute the classification error of this split.
# Error = (# of mistakes (left) + # of mistakes (right)) / (# of data points)
## YOUR CODE HERE
error = (nMistakesLft + nMistakesRgt) / nObs
# If this is the best error we have found so far,
# store the feature as featureBest and the error as errorBest
## YOUR CODE HERE
if error < errorBest:
featureBest = feature
errorBest = error
return featureBest # Return the best feature we found
To test your getFeatureSplitBest function, run the following code:
if getFeatureSplitBest(glbObsFit, features, 'safe_loan') == 'term. 36 months':
print 'Test passed!'
else:
print 'Test failed... try again!'
With the above functions implemented correctly, we are now ready to build our decision tree. Each node in the decision tree is represented as a dictionary which contains the following keys and possible values:
{
'isLeaf' : True/False.
'prediction' : Prediction at the leaf node.
'left' : (dictionary corresponding to the left tree).
'right' : (dictionary corresponding to the right tree).
'featureSplit' : The feature that this node splits on.
}
First, we will write a function that creates a leaf node given a set of target values. Fill in the places where you find ## YOUR CODE HERE. There are three places in this function for you to fill in.
def bldLeaf(targetVctr):
# Create a leaf node
leaf = {'featureSplit' : None,
'left' : None,
'right' : None,
'isLeaf' : True} ## YOUR CODE HERE
# Count the number of data points that are +1 and -1 in this node.
nPls = len(targetVctr[targetVctr == +1])
nMns = len(targetVctr[targetVctr == -1])
# For the leaf node, set the prediction to be the majority class.
# Store the predicted class (1 or -1) in leaf['prediction']
if nPls > nMns:
leaf['prediction'] = +1 ## YOUR CODE HERE
else:
leaf['prediction'] = -1 ## YOUR CODE HERE
# Return the leaf node
return leaf
print(bldLeaf(gl.SArray([-1, -1, +1, +1, +1])))
print(bldLeaf(gl.SArray([-1, -1, -1, +1, +1, +1])))
print(bldLeaf(gl.SArray([-1, -1, -1, +1, +1])))
We have provided a function that learns the decision tree recursively and implements 3 stopping conditions:
Now, we will write down the skeleton of the learning algorithm. Fill in the places where you find ## YOUR CODE HERE. There are seven places in this function for you to fill in.
def bldDecisionTree(data, features, target, depthCur = 0, depthMax = 10):
featureRemain = features[:] # Make a copy of the features.
targetVctr = data[target]
print "--------------------------------------------------------------------"
print "Subtree, depth = %s (%s data points)." % (depthCur, len(targetVctr))
# Stopping condition 1
# (Check if there are mistakes at current node.
# Recall you wrote a function getNMistakesIntermediateNode to compute this.)
if getNMistakesIntermediateNode(targetVctr) == 0: ## YOUR CODE HERE
print "Stopping condition 1 reached."
# If no mistakes at current node, make current node a leaf node
return bldLeaf(targetVctr)
# Stopping condition 2 (check if there are remaining features to consider splitting on)
if len(featureRemain) == 0: ## YOUR CODE HERE
print "Stopping condition 2 reached."
# If there are no remaining features to consider, make current node a leaf node
return bldLeaf(targetVctr)
# Additional stopping condition (limit tree depth)
if depthCur >= depthMax: ## YOUR CODE HERE
print "Reached maximum depth. Stopping for now."
# If the max tree depth has been reached, make current node a leaf node
return bldLeaf(targetVctr)
# Find the best splitting feature (recall the function getFeatureSplitBest implemented above)
## YOUR CODE HERE
featureSplitBest = getFeatureSplitBest(data, features, target)
# Split on the best feature that we found.
splitLft = data[data[featureSplitBest] == 0]
splitRgt = data[data[featureSplitBest] != 0] ## YOUR CODE HERE
featureRemain.remove(featureSplitBest)
print "Split on feature %s. (%s, %s)" % (\
featureSplitBest, len(splitLft), len(splitRgt))
# Create a leaf node if the split is "perfect"
if len(splitLft) == len(data):
print "Creating leaf node."
return bldLeaf(splitLft[target])
if len(splitRgt) == len(data):
print "Creating leaf node."
## YOUR CODE HERE
return bldLeaf(splitRgt[target])
# Repeat (recurse) on left and right subtrees
treeLft = bldDecisionTree(splitLft, featureRemain, target, depthCur + 1, depthMax)
## YOUR CODE HERE
treeRgt = bldDecisionTree(splitRgt, featureRemain, target, depthCur + 1, depthMax)
return {'isLeaf' : False,
'prediction' : None,
'featureSplit': featureSplitBest,
'left' : treeLft,
'right' : treeRgt}
Here is a recursive function to count the nodes in your tree:
def getNNodes(tree):
if tree['isLeaf']:
return 1
return 1 + getNNodes(tree['left']) + getNNodes(tree['right'])
Run the following test code to check your implementation. Make sure you get 'Test passed' before proceeding.
smallDataDTree = bldDecisionTree(glbObsFit, features, 'safe_loan', depthMax = 3)
if getNNodes(smallDataDTree) == 13:
print 'Test passed!'
else:
print 'Test failed... try again!'
print 'Number of nodes found :', getNNodes(smallDataDTree)
print 'Number of nodes that should be there : 13'
Now that all the tests are passing, we will train a tree model on the glbObsFit. Limit the depth to 6 (depthMax = 6) to make sure the algorithm doesn't run for too long. Call this tree glbObsFitDTree.
Warning: This code block may take 1-2 minutes to learn.
# Make sure to cap the depth at 6 by using depthMax = 6
glbObsFitDTree = bldDecisionTree(glbObsFit, features, 'safe_loan', depthMax = 6)
As discussed in the lecture, we can make predictions from the decision tree with a simple recursive function. Below, we call this function classifyDTree, which takes in a learned tree and a test point x to classifyDTree. We include an option annotate that describes the prediction path when set to True.
Fill in the places where you find ## YOUR CODE HERE. There is one place in this function for you to fill in.
def classifyDTree(tree, x, annotate = False):
# if the node is a leaf node.
if tree['isLeaf']:
if annotate:
print "At leaf, predicting %s" % tree['prediction']
return tree['prediction']
else:
# split on feature.
featureSplitVal = x[tree['featureSplit']]
if annotate:
print "Split on %s = %s" % (tree['featureSplit'], featureSplitVal)
if featureSplitVal == 0:
return classifyDTree(tree['left' ], x, annotate)
else:
return classifyDTree(tree['right'], x, annotate)
### YOUR CODE HERE
Now, let's consider the first example of the test set and see what glbObsFitDTree model predicts for this data point.
glbObsOOB[0]
print 'Predicted class: %s ' % classifyDTree(glbObsFitDTree, glbObsOOB[0])
Let's add some annotations to our prediction to see what the prediction path was that lead to this predicted class:
classifyDTree(glbObsFitDTree, glbObsOOB[0], annotate=True)
Quiz question: What was the feature that glbObsFitDTree first split on while making the prediction for glbObsOOB[0]?
Quiz question: What was the first feature that lead to a right split of glbObsOOB[0]?
Quiz question: What was the last feature split on before reaching a leaf node for glbObsOOB[0]?
Now, we will write a function to evaluate a decision tree by computing the classification error of the tree on the given dataset.
Again, recall that the classification error is defined as follows: $$ \mbox{classification error} = \frac{\mbox{# mistakes}}{\mbox{# total examples}} $$
Now, write a function called evlClassificationError that takes in as input:
tree (as described above)data (an SFrame)This function should return a prediction (class label) for each row in data using the decision tree. Fill in the places where you find ## YOUR CODE HERE. There is one place in this function for you to fill in.
def evlClassificationError(tree, data):
# Apply the classifyDTree(tree, x) to each row in your data
prediction = data.apply(lambda x: classifyDTree(tree, x))
# Once you've made the predictions, calculate the classification error and return it
## YOUR CODE HERE
return(data[data[target] != prediction].shape[0] * 1.0 / data.shape[0])
Now, let's use this function to evaluate the classification error on the test set.
evlClassificationError(glbObsFitDTree, glbObsOOB)
Quiz Question: Rounded to 2nd decimal point, what is the classification error of glbObsFitDTree on the glbObsOOB?
As discussed in the lecture, we can print out a single decision stump (printing out the entire tree is left as an exercise to the curious reader).
def dspDTreeStump(tree, name = 'root'):
split_name = tree['featureSplit'] # split_name is something like 'term. 36 months'
if split_name is None:
print "(leaf, label: %s)" % tree['prediction']
return None
split_feature, split_value = split_name.split('.')
print ' %s' % name
print ' |---------------|----------------|'
print ' | |'
print ' | |'
print ' | |'
print ' [{0} == 0] [{0} == 1] '.format(split_name)
print ' | |'
print ' | |'
print ' | |'
print ' (%s) (%s)' \
% (('leaf, label: ' + str(tree['left']['prediction']) if tree['left']['isLeaf'] else 'subtree'),
('leaf, label: ' + str(tree['right']['prediction']) if tree['right']['isLeaf'] else 'subtree'))
dspDTreeStump(glbObsFitDTree)
Quiz Question: What is the feature that is used for the split at the root node?
The tree is a recursive dictionary, so we do have access to all the nodes! We can use
glbObsFitDTree['left'] to go leftglbObsFitDTree['right'] to go rightdspDTreeStump(glbObsFitDTree['left'], glbObsFitDTree['featureSplit'])
dspDTreeStump(glbObsFitDTree['left']['left'], glbObsFitDTree['left']['featureSplit'])
Quiz question: What is the path of the first 3 feature splits considered along the left-most branch of glbObsFitDTree?
Quiz question: What is the path of the first 3 feature splits considered along the right-most branch of glbObsFitDTree?
print(dspDTreeStump(glbObsFitDTree['right'], glbObsFitDTree['featureSplit']))
print(dspDTreeStump(glbObsFitDTree['right']['right'], glbObsFitDTree['right']['featureSplit']))